<?php

namespace App\Http\Controllers;

use App\Http\Models\Mysql\NnyyUserTable;
use App\Http\Repository\CommonRepository;
use App\Http\Repository\FeishuRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class LoginController
{
    public function login(Request $request)
    {
        $param = $request->all();
        list($username, $password, $sourceFrom) = [$param['username'] ?? $param['name'], $param['password'], $param['source_from']];
        //飞书扫码登录模式，需要确认飞书用户是否存在
        if($param['source_from'] == 'fs' && ($username['code'] ?? "")){
            list($code, $isSubject) = [$username['code'], $username['state']];
            $fsUserRes = (new FeishuRepository($isSubject))->getUserInfo($code);
            //根据飞书返回的用户信息去数据库进行对比
            if($fsUserRes['code'] !=0 ){
                return error('登陆失败, 飞书用户不存在！');
            }
            $whereUser = ["{$isSubject}_feishu_union_id" => $fsUserRes['data']['union_id']];
            $userRes = (new NnyyUserTable())->where($whereUser)->first();
            if(empty($userRes)){
                return error("登陆失败, 飞书用户未同步！");
            }
            $userRes = $userRes->toArray();
            $username = $userRes['name'];
            $password = $userRes['phone'];
            (new NnyyUserTable())->updateData($userRes['id'], ['is_subject' => $isSubject]);
        }
        if (!Auth()->attempt(['name' => $username, 'phone' => $password, 'password' => $password, 'source_from' => $sourceFrom])) {
            return error("登录失败, 请确认用户是否存在");
        }
        $user = $request->user();
        if($user['status'] !== 1){
            return error("登录失败, 该用户已禁用");
        }
        //登录频繁操作设置
        $res = CommonRepository::detectClientId("login_".$request->getClientIp().":{$username}", 30);
        if($res['code'] !== 0){
            return error("登录失败：".$res['msg']);
        }
        $tokenResult = $user->createToken('Personal Access Token');

        return success("获取登录token", [
            'token' => $tokenResult->accessToken,
            'expires_in' => Carbon::parse($tokenResult->token->expires_at)->toDateTimeString()
        ]);
    }

    public function logout()
    {
        if(!empty(auth()->guard("api")->user())){
            auth()->guard("api")->user()->token()->revoke();
        }
        return success("退出登录");
    }

    //登录调整地址
    public function redirectUri()
    {
        $appEnv = env("APP_ENV");
        //线上环境
        if($appEnv == "PRO"){
            $uri = "https%3A%2F%2Fnnyy.13yu.com%2F%23%2Flogin%3Fon%3Dloading";
            return result($uri,"登录跳转地址");
        }else{
            $uri = urlencode($_SERVER['HTTP_ORIGIN'])."%2F%23%2Flogin%3Fon%3Dloading";
            return result($uri, "登录跳转地址");
        }
    }
}
